<script setup>
import {useApi} from "../../composables/useApi"
import showTost from '@/components/toast/index.js'
import * as XLSX from "xlsx";
import {storeToRefs} from "pinia"
import {useAppStore} from "../../store/app"
import moment from "moment";

const appStore = useAppStore()

const {nationArr, sexArr} = storeToRefs(appStore)
import {reactive, ref} from "vue"
import ClassHeader from "@/pages/platform/components/classHeader.vue";
import HonorRightDrawear from "@/pages/platform/components/honorRightDrawear.vue";
import {router} from "@/plugins/1.router/index.js";
import {getGradeListAll} from "@/api/standard.js";
//基本数据list
let list = ref([])
let page = ref(1)
let limit = ref(20)
let total = ref(0)//总数
const selected = ref([])
let queryFrom = ref({page: 1, limit: 20, title: '', name: ''})

const headers = [
  {
    title: "荣誉图标",
    key: "icon",
    align: 'start',
  },
  {
    title: "荣誉名称",
    key: "title",
    align: 'start',
  },
  {
    title: "关联分数类型",
    key: "scoreType",
    align: 'start',
  },
  {
    title: "获得方式",
    key: "mode",
    align: 'start',
  },
  {
    title: "获得分数",
    key: "score",
    align: 'start',
  },
  {
    title: "前具体排名",
    key: "ranking",
    align: 'start',
  },
  {
    title: "前百分比排名",
    key: "percent",
    align: 'start',
  },
  {
    title: "面向范围",
    key: "edRadius",
    align: 'start',
  },
  {
    title: "已获得人数",
    key: "num",
    align: 'start',
  },
  {
    title: "操作",
    align: 'end',
    key: "options",
    sortable: false,
  },
]

const getList = async () => {
  const {data} = await useApi('/admin/Api.Honor/index').post(queryFrom.value)
  console.log(data)
  total.value = data.value.data.total
  list.value = data.value.data.data.map(item => {
    return {
      ...item, id: item.honor_id
    }
  })
  console.log(list.value)
}

const dialogFlag = ref(false)
// 头部表单回调
const onChange = val => {
  let data = JSON.parse(JSON.stringify(val))
  queryFrom.value = {...queryFrom.value, ...data}
  getList()
}
const isConfirmDialogVisible = ref(false)
// 删除确认弹窗
const onHandleDelete = async (val) => {
  console.log(val)
  let ids = val.data.map(item => item.honor_id).toString()
  console.log(ids)
  const {data} = await useApi('/admin/Api.Honor/delete').post({honor_id: ids})
  console.log(data.value)
  if (data.value.status == 200) {
    showTost("删除成功", {duration: 3000, type: "success"})
    queryFrom.value.page = 1
    isConfirmDialogVisible.value = false
    if (val.type == 'detail') {
      dialogFlag.value = false
    }
    getList()
  }
}
const selectedItems = ref([]);

// 确认弹窗文本
const confirmMsg = ref('')

// 打开删除弹窗
const onHandleDialog = (type) => {
  if (type == 'delete') {
    console.log(selectedItems)
    if (selectedItems.value.length == 0) return
    let data = list.value.filter(item => selectedItems.value.find(val => val == item.id))
    console.log(data)
    currentOptionData.value = {
      data: data,
      type: 'list'
    }
    confirmMsg.value = `确认删除${data.map(item => item.title).toString()}的信息吗`
    isConfirmDialogVisible.value = true
  } else {
    addDialogFlag.value = true
  }
}
// 详情数据
const detailData = ref({})
const viewDetail = async (item) => {
  const {data} = await useApi('/admin/Api.Honor/detail').post({honor_id: item.honor_id})
  console.log(data)
  data.value.data.scoreType = Number(data.value.data.scoreType)
  detailData.value = data.value.data
  dialogFlag.value = true
}
// 添加教师弹窗falg
const addDialogFlag = ref(false)
const refVForm = ref()

// 下载模板
const downLoadTemplate = async () => {
  const {data} = await useApi('/admin/Base/downFile').post({type: 1})
  console.log(data.value)
  if (data.value.status == 200) {
    const link = document.createElement('a');
    link.href = data.value.data.fileUrl;
    link.download = data.value.data.fileName;
    link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
    link.click();

  }
}
// 新增取消回调
const resetForm = () => {
  refVForm.value?.reset()

  addDialogFlag.value = false
}


const valid = ref(false)
const form = reactive({
  title: '',
  icon: '',
  scoreType: 1,
  mode: 1,
  conditions: null,
  score: '',
  ranking: '',
  percent: '',
  scoreValue: null,
  edRadius: [],
  classId: null,
})
// const gradeList = ref([])
// getGradeListAll().then(res => {
//   gradeList.value = res.data
//   console.log(gradeList.value)
//   debugger
// })
const confirmAddTeacher = async (args) => {
  console.log(valid.value)
  console.log(form.classId)

  if (!valid.value) return
  console.log(form.classId)
  if(form.classId.find(item=>item==-1)){
    form.edRadius = 1
  }else{
    form.edRadius = 2
  }
  const {data} = await useApi('/admin/Api.Honor/add').post(form)
  if (data.value.status == 200) {
    refVForm.value?.reset()
    addDialogFlag.value = false
    showTost("新增成功", {duration: 3000, type: "success"})
    queryFrom.value.page = 1
    await getList()
  } else {
    console.log(data.value.msg)
    // showTost("新增成功", {duration: 3000, type: "success"})

    showTost(data.value.msg, {duration: 3000, type: "error"})
  }
}
let sexList = ref(['男', '女'])
const onHandleEdit = () => {
  dialogFlag.value = false
  queryFrom.value.page = 1
  getList()
}
getList()
const required = (value, name) => !!value || `${name}为必填字段`;
const importExcelRef = ref(null)
const httpRequest = (e) => {
  let file = e.file // 文件信息
  if (!file) {
    return false
  } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    // 格式根据自己需求定义
    this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
    return false
  }
  const fileReader = new FileReader()
  fileReader.onload = (ev) => {
    try {
      const data = ev.target.result
      const workbook = XLSX.read(data, {
        // 以字符编码的方式解析
        type: 'binary',
        cellDates: true,

      })
      // 取第一张表
      console.log(workbook)
      const exlname = workbook.SheetNames[0]
      const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]) // 生成json表格内容
      console.log(exl)
      partPost(exl)
      // 将 JSON 数据挂到 data 里
      let arr = []
      exl.forEach(item => {
        arr.push(item.name)
      })
      console.log(arr)
    } catch (e) {
      console.log('error')
      return false
    }
  }
  fileReader.readAsBinaryString(file)
}
const import_page = ref(1)
const import_limit = ref(10)
const import_percent = ref(0)
const loading = ref(false)

const partPost = async (tableData) => {
  let perdata = []
  for (let i = (import_page.value - 1) * import_limit.value; i < import_page.value * import_limit.value; i++) {
    if (tableData[i]) {
      perdata.push(tableData[i])
    }
  }
  let total_page = Math.ceil(tableData.length / import_limit.value)
  import_percent.value = Math.ceil(import_page.value * 100 / total_page)
  loading.value = true
  console.log(perdata)
  perdata = perdata.map(item => {
    return {
      ...item,
      '出生日期': convertExcelDateFormat(item, '出生日期'),
      '入职日期': convertExcelDateFormat(item, '入职日期'),
    }
  })
  console.log(perdata)
  const {data} = await useApi('/admin/Api.Teacher/upload').post({list: perdata})
  if (data.value.status == 200) {
    if (import_page.value <= total_page - 1) {
      import_page.value = import_page.value + 1
      partPost(data)
    } else {
      // this.dialog.importDialogstatus = false;
      showTost("导入完成", {duration: 3000, type: "success"})
      addDialogFlag.value = false
      queryFrom.value.page = 1
      getList()
      loading.value = false
    }
  }
  // importData(perdata).then(res => {
  //   if(res.status == 200){
  //     if(this.import_page <= total_page-1){
  //       this.import_page = this.import_page +1
  //       this.partPost(data)
  //     }else{
  //       this.dialog.importDialogstatus = false;
  //       this.$message({message: '导入完成', type: 'success'})
  //       this.index()
  //       this.loading = false
  //     }
  //   }
  // })
}

const onChangePage = (val) => {
  queryFrom.value.page = val.page
  queryFrom.value.limit = val.limit
  getList()
}
const convertExcelDateFormat = (row, columnName) => {
  //日期转换
  var date = row[columnName]
  if (date === undefined || date === null || date === "") {
    return null;
  }
  console.log(date)
  //非时间格式问题  返回Invalid date
  let retFormat = moment(date).format('YYYY-MM-DD');
  if (retFormat === "Invalid date") {
    return retFormat;
  }
  return moment(date).add(1, 'days').format('YYYY-MM-DD')
}
const currentOptionData = ref({})
const drawaerDelete = async (val) => {
  console.log(val)
  currentOptionData.value = {
    data: [val],
    type: 'detail'
  }
  confirmMsg.value = `确认删除${val.title}的信息吗`
  isConfirmDialogVisible.value = true
}
// 获取教师列表开始
const teacherList = ref([])
const getTeacherList = async () => {
  const {data} = await useApi('/admin/Api.Teacher/indexList').post({})
  if (data.value.status == 200) {
    teacherList.value = data.value.data
  }
}
getTeacherList()
// 获取教师列表结束

// 获取年级列表开始
const gradeList = ref([])
const getGradeList = async () => {
  const {data} = await useApi('/admin/Api.Grade/indexList').post({})
  if (data.value.status == 200) {
    console.log(data.value.data)
    gradeList.value = data.value.data
    gradeList.value.unshift({grade_id:-1,title:'全校'})
  }
}
getGradeList()
// 获取年级列表结束

const goRecord = (item)=>{
  router.push(`/platform/honorSecondList?id=${item.honor_id}&title=${item.title}`)
  // router.push( '/platform/times-manage?type=1')

//    todo 去记录页
}
const projectType = ref([{title:'标化成绩',value:1},{title:'素质分数',value:2}])

const projectList = ref([{title:'英语',value:1},{title:'数学',value:2},{title:'语文',value:3},{title:'美术',value:4},{title:'总分',value:5}],

  )
const qualityList = [{title:'智',value:1},{title:'体',value:1},
  {title:'美',value:1},{title:'劳',value:1}]

const getTypeList = ref([{title:'分值',value:1},{ title:'排名',value:2},{ title:'百分比排名',value:3}])


const judgment = ref([{title:'>=',value:1},{ title:'=',value:2},{ title:'>',value:3},{ title:'<',value:4},{ title:'<=',value:5}])

const onlyAllowNumbers = (event) => {
  const key = event.key;
  // 检查按键是否为数字或控制键（如 backspace）
  if (!/^\d$/.test(key) && event.key !== 'Backspace' && event.key !== 'Tab') {
    event.preventDefault();
  }
}
const filterInput =(key) => {
  // 仅保留数字
  form[key] = form[key].replace(/\D/g, '');
}

</script>

<template>
  <div class="content">
    <honor-right-drawear  :gradeList="gradeList" :teacher-list="teacherList" @onHandleDelete="drawaerDelete"  @onHandleEdit="onHandleEdit"
                   :detailData="detailData" @update:isDrawerOpen="dialogFlag=$event"
                   :is-drawer-open="dialogFlag" ></honor-right-drawear>

    <ConfirmDialog
      v-model:isDialogVisible="isConfirmDialogVisible"
      :handleData="currentOptionData"
      @confirm="onHandleDelete"
      :confirm-msg="confirmMsg"
      :confirmation-question="confirmMsg"
      cancel-msg="Unsubscription Cancelled!!"
    />
    <!-- 头部 -->
    <custom-header title="荣誉列表"
                  button-text="添加荣誉"
                  @onChange="onChange"
                  @onHandle="onHandleDialog"></custom-header>


    <VDataTable
      v-model="selectedItems"
      :headers="headers"
      :items="list"
      :items-per-page="100"
      item-key="id"
      show-select
      class="text-no-wrap"
    >
      <template #item.icon="{ item }">
        <div class="d-flex align-center " style="margin: 10px; 0 ">
          <div class="d-flex flex-column  ">
            <img style="width: 64px" :src="item.icon" alt="">
          </div>
        </div>
      </template>
      <template #item.scoreType="{ item }" >
        <div class="d-flex align-center " style="margin: 10px; 0 ">
          <div class="d-flex flex-column  ">
            <div>{{item.scoreType ==1?'标化分数':'素质分数'}}</div>
          </div>
        </div>
      </template>
      <template #item.edRadius="{ item }">
        <div class="d-flex align-center " style="margin: 10px; 0 ">
          <div class="d-flex flex-column  ">
            <div>{{item.edRadius ==1?'全校':'年级'}}</div>
          </div>
        </div>
      </template>
      <template #item.mode="{ item }">
        <div class="d-flex align-center " style="margin: 10px; 0 ">
          <div class="d-flex flex-column  ">
            <div>{{item.edRadius ==1?'分值':item.edRadius ==2?'排名':'百分比排名'}}</div>
          </div>
        </div>
      </template>
<!--      <template #item.ranking="{ item }" v-if="item.mode==2">-->
<!--        <div class="d-flex align-center " style="margin: 10px; 0 ">-->
<!--          <div class="d-flex flex-column">-->
<!--            <div>{{item.ranking}}</div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </template>-->

      <template #item.options="{ item }">
        <div class="d-flex align-center options-right-display">
          <div class="d-flex align-center ms-3 cursor-pointer">
            <div @click="goRecord(item,)" class="me-4 cursor-pointer">获得记录</div>
            <i @click="viewDetail(item)" class="ri-menu-line"></i>
          </div>
        </div>
      </template>
    </VDataTable>
    <PaginationVue
      @onChange="onChangePage"
      :current-page="queryFrom.page"
      :page-size="queryFrom.limit"
      :total="total"
    />

    <!--    添加对话框-->
    <VDialog
      :persistent="true"
      max-width="600"
      :model-value="addDialogFlag"
    >
      <div class="dialog-body" style="width: 600px">
        <AppDrawerHeaderSection
          title="添加荣誉"
          @cancel="addDialogFlag=false"
        />
        <VDivider style="background-color: red" class="v-divider"/>
        <VCard>
          <PerfectScrollbar
            :options="{ wheelPropagation: false }"
            class="h-60"
          >
            <VCardText>

              <VForm
                v-model="valid"
                ref="refVForm"
                @submit.prevent="confirmAddTeacher"
              >
                <VRow>
                  <VCol cols="6">
                    <VTextField
                      v-model="form.title"
                      label="荣誉名称"
                      :rules="[(val)=>required(val,'荣誉名称')]"
                    >
                      <template v-slot:label>
                        <span>荣誉名称</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VTextField>
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.scoreType"
                      :items="projectType"
                      item-title="title"
                      item-value="value"
                      :rules="[(val)=>required(val,'关联分数类型')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>关联分数类型</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VSelect>
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.scoreValue"
                      :items="form.scoreType==1?projectList:qualityList"
                      item-title="title"
                      item-value="value"
                      :rules="[(val)=>required(val,'关联项目')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>关联项目</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VSelect>
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.mode"
                      :items="getTypeList"
                      item-title="title"
                      item-value="value"
                      :rules="[(val)=>required(val,'获取方式')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>获取方式</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VSelect>
                  </VCol>
                  <VCol cols="6">
                    <VSelect
                      v-model="form.conditions"
                      :items="judgment"
                      item-title="title"
                      item-value="value"
                      :rules="[(val)=>required(val,'判断条件')]"
                      class="input-width-height"
                    >
                      <template v-slot:label>
                        <span>判断条件</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VSelect>
                  </VCol>
                  <VCol cols="6">
                    <VTextField
                      v-if="form.mode==1"
                      v-model="form.score"
                      label="具体分数"
                      @keypress="onlyAllowNumbers"
                      @input="()=>filterInput('score')"
                      :rules="[(val)=>required(val,'具体分数')]"
                      placeholder="请输入具体分数"
                    >
                      <template v-slot:label>
                        <span>具体分数</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VTextField>
                    <VTextField
                      v-if="form.mode==2"
                      v-model="form.ranking"
                      label="前具体排名"
                      @keypress="onlyAllowNumbers"
                      @input="()=>filterInput('ranking')"
                      :rules="[(val)=>required(val,'前具体排名')]"
                      placeholder="请输入前具体排名"
                    >
                      <template v-slot:label>
                        <span>前具体排名</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VTextField>
                    <VTextField
                      v-if="form.mode==3"
                      v-model="form.percent"
                      label="前百分比排名"
                      @keypress="onlyAllowNumbers"
                      @input="()=>filterInput('percent')"
                      :rules="[(val)=>required(val,'前百分比排名')]"
                      placeholder="请输入前百分比排名"
                    >
                      <template v-slot:label>
                        <span>前百分比排名</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </VTextField>
                  </VCol>
                  <VCol cols="6">
                    <v-autocomplete
                      label="面向范围"
                      v-model="form.classId"
                      item-title="title"
                      item-value="grade_id"
                      :items="gradeList"
                      multiple
                      variant="outlined"
                    >
                      <template v-slot:label>
                        <span>面向范围</span>
                        <span  style="color: red;margin-left: 4px;">*</span>
                      </template>
                    </v-autocomplete>
                  </VCol>
                  <VCol cols="12" style="padding: 0">

                   </VCol>
                  <VCol cols="12">
                    <div class="mb-1">荣誉图标</div>
                    <upload-ohter-img
                      style="width:100%;"
                      :limit="1"
                      :value="form.icon"
                      @input="(val) => {form.icon = val}"
                    />
                  </VCol>
                  <VCol cols="12">
                    <div class="d-flex justify-end">
                      <VBtn
                        color="secondary"
                        type="reset"
                        variant="tonal"
                        class="me-4"
                        @click="resetForm"
                      >
                        取消
                      </VBtn>
                      <VBtn
                        type="submit"
                        color="primary"
                        class="me-4"
                      >
                        添加
                      </VBtn>
                    </div>
                  </VCol>
                </VRow>
              </VForm>
            </VCardText>
          </PerfectScrollbar>
        </VCard>

      </div>
    </VDialog>
  </div>

</template>

<style lang="scss" scoped>
.dialog-body{
  background: rgb(var(--v-theme-surface));
}
</style>
